package com.yunquan.ohana.ui.main

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.view.KeyEvent
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.fragment.app.Fragment
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.bus.RxBus
import com.yunquan.ohana.base.ui.BaseActivity
import com.yunquan.ohana.databinding.ActivityMainBinding
import com.yunquan.ohana.entity.EventEntity
import com.yunquan.ohana.entity.EventType
import com.yunquan.ohana.service.DataUploadService
import com.yunquan.ohana.ui.history.HistoryFragment
import com.yunquan.ohana.ui.home.HomeFragment
import com.yunquan.ohana.ui.mine.MineFragment
import com.yunquan.ohana.utils.L
import com.yunquan.ohana.utils.SPUtils
import java.util.Locale
import kotlin.system.exitProcess

class MainActivity : BaseActivity<ActivityMainBinding, MainViewModel>() {

    private val mFragments = mutableListOf<Fragment>()
    private var mFragment: Fragment? = null

    private var oldTime: Long = 0

    private var mService: DataUploadService? = null

    private val mDataUploadServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
            if (p1 is DataUploadService.DataUploadBinder) {
                mService = p1.getService()
            }
        }

        override fun onServiceDisconnected(p0: ComponentName?) {
        }

    }

    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_main
    }

    override fun initVariableId(): Int {
        return BR.mainViewModel
    }

    override fun initParam() {
        super.initParam()
        Locale.setDefault(Locale("en"))
        // 设置背景颜色
        window.statusBarColor = ContextCompat.getColor(this, R.color.c_F6)
        // 设置文字颜色（true = 黑色文字，false = 白色文字）
        val controller = WindowInsetsControllerCompat(window, window.decorView)
        controller.isAppearanceLightStatusBars = true
    }

    override fun onResume() {
        super.onResume()
        if (!isServiceRunning(DataUploadService::class.java)) {
            L.i("重启数据上传服务")
            startBindService()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(mDataUploadServiceConnection)
    }

    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)
        SPUtils.put("firstStart", false)
        startBindService()
        mFragments.apply {
            add(HomeFragment.newInstance())
            add(HistoryFragment.newInstance())
            add(MineFragment.newInstance())
        }
        val transaction = supportFragmentManager.beginTransaction()
        mFragments.forEach {
            transaction.add(R.id.fl_content, it)
        }
        transaction.commit()
        checkPager(0)

        binding!!.rgPager.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.rb_frames -> checkPager(0)
                R.id.rb_history -> checkPager(1)
                R.id.rb_mine -> checkPager(2)
            }
        }
    }

    override fun initViewObservable() {
        super.initViewObservable()
        viewModel!!.ui.observe(this) { type ->
            when (type) {
                0 -> {
                    binding!!.rbHistory.isChecked = true
                    checkPager(1)
                }
            }
        }
    }

    private fun checkPager(type: Int) {
        val transaction = supportFragmentManager.beginTransaction()
        mFragments.forEach {
            transaction.hide(it)
        }
        mFragment = mFragments[type]
        transaction.show(mFragment!!)
        transaction.commit()

        if (mFragment is HistoryFragment) {
            RxBus.getDefault().post(EventEntity(EventType.FRESH_HISTORY_COMPLETED))
        } else if (mFragment is HomeFragment) {
            (mFragment as HomeFragment).viewModel?.getFrames()
        } else if (mFragment is MineFragment) {
            (mFragment as MineFragment).viewModel?.getUserInfo()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - oldTime > 2000) {
                oldTime = System.currentTimeMillis()
                return true
            } else {
                exitProcess(0)
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun startBindService() {
        val intent = Intent(this, DataUploadService::class.java)
        bindService(intent, mDataUploadServiceConnection, BIND_AUTO_CREATE)
    }

    private fun isServiceRunning(serviceClass: Class<*>): Boolean {
        val manager = getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
        for (service in manager.getRunningServices(Int.MAX_VALUE)) {
            if (serviceClass.name == service.service.className) {
                return true
            }
        }
        return false
    }
}